package com.example.lleon.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends Activity {

    // 声明ListView
    private ListView mListView;

//    private static String URL = "http://123.207.0.81:9001";
    private static String url = "http://192.168.31.132:8080/test/";
    Date date = new Date();
    String dates = new SimpleDateFormat("yyMMdd").format(date);
    private String cpURL = url + "complex/" + dates;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 定义用于装载JSON数据的ListVIew
        mListView = (ListView) findViewById(R.id.lv_main);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final TextView url_tv=(TextView) view.findViewById(R.id.tv_url);
                Intent jump=new Intent(MainActivity.this,webViewer.class);
                jump.putExtra("webjumper",url_tv.getText().toString());
                startActivity(jump);
            }
        });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final TextView banana_tv=(TextView) view.findViewById(R.id.tv_bananas);
                final TextView onlooker_tv=(TextView) view.findViewById(R.id.tv_views);
                final TextView comments_tv=(TextView) view.findViewById(R.id.tv_comments);
                Toast.makeText(MainActivity.this, "香蕉:" + banana_tv.getText().toString() +
                "  围观:" + onlooker_tv.getText().toString() +
                "  评论:" + comments_tv.getText().toString(), Toast.LENGTH_SHORT).show();
                return true;              //返回true将不会触发OnItemClickListener
            }
        });
        // 实例化AsyncTask，并请求网络数据加载
        new ArticleAsyncTask().execute(cpURL);
    }

    /*
    * 创建AsyncTask用于请求网络数据加载
    * */
    class ArticleAsyncTask extends AsyncTask<String, Void, List<ArticleBean>> {
        @Override
        protected List<ArticleBean> doInBackground(String... params) {
            try {
                return getJsonData(params[0]);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        @Override
        protected void onPostExecute(List<ArticleBean> articleBeans) {
            super.onPostExecute(articleBeans);
            /*
            * 实例化Adapter，为ListView填充数据
            * */
            ArticleAdapter adapter = new ArticleAdapter(MainActivity.this, articleBeans);
            mListView.setAdapter(adapter);
        }
    }

    /*
    * 根据url来获取并解析JSON数据
    * */
    private List<ArticleBean> getJsonData(String url) throws IOException {
        List<ArticleBean> articleBeanList = new ArrayList<>();
        /*
        * 获取JSON并解析JSON
        *
        * JSON数据格式为：
        * {"pages":[
        *   {"page-id":"3316198","url":"http://www.acfun.tv/a/ac3316198","title":"8分钟永久恢复视力 比普通人视力增强3倍","ac-id":"ac3316198","onlooker":74109,"comments":370,"banana":5},
        *   {"page-id":"3316800","url":"http://www.acfun.tv/a/ac3316800","title":"东莞运钞车被砸案细节公开：押运员多次警告别砸车","ac-id":"ac3316800","onlooker":52933,"comments":1236,"banana":1},
        *   {"page-id":"3316254","url":"http://www.acfun.tv/a/ac3316254","title":"中国核聚变获重大突破 燃烧温度比太阳都高破纪录","ac-id":"ac3316254","onlooker":66115,"comments":517,"banana":16},
        *   {"page-id":"3317624","url":"http://www.acfun.tv/a/ac3317624","title":"小鲜肉被曝订做“人皮面具” 只为演戏便于用替身","ac-id":"ac3317624","onlooker":46731,"comments":217,"banana":1},
        *   {"page-id":"3317164","url":"http://www.acfun.tv/a/ac3317164","title":"120岁世界最长寿男人：至今仍是“童子身”","ac-id":"ac3317164","onlooker":63719,"comments":219,"banana":21},
        *   {"page-id":"3316642","url":"http://www.acfun.tv/a/ac3316642","title":"日媒：外国人为什么不觉得中国菜好吃？","ac-id":"ac3316642","onlooker":135730,"comments":1358,"banana":21},
        *   {"page-id":"3317111","url":"http://www.acfun.tv/a/ac3317111","title":"王思聪开撕权志龙：就几个纹身显摆！滚回韩国去","ac-id":"ac3317111","onlooker":106119,"comments":804,"banana":6},
        *   {"page-id":"3317263","url":"http://www.acfun.tv/a/ac3317263","title":"东北爷们遇南方蟑螂立马怂？一条微博引发集体共鸣","ac-id":"ac3317263","onlooker":73138,"comments":759,"banana":9},
        *   {"page-id":"3316421","url":"http://www.acfun.tv/a/ac3316421","title":"如果发生战争，哪些现代国家的军队绝对不能低估？ [美国媒体]","ac-id":"ac3316421","onlooker":45157,"comments":383,"banana":4}
        *   ]}
        * */
        String jsonString;
        try {
            jsonString = readStream(new URL(url).openStream());
            JSONObject jsonObject;
            ArticleBean articleBean;
            jsonObject = new JSONObject(jsonString);
            JSONArray jsonArray = jsonObject.getJSONArray("data");

            /*
            * 逐行解析JSON数据
            * */
            for(int i = 0; i < jsonArray.length(); i++) {
                jsonObject = jsonArray.getJSONObject(i);
                articleBean = new ArticleBean();

                articleBean.acTitle = jsonObject.getString("title");
                articleBean.acId = jsonObject.getString("aid");
                articleBean.acUrl = jsonObject.getString("url");

                articleBean.acViews = jsonObject.getString("views");
                articleBean.acBananas = jsonObject.getString("bananas");
                articleBean.acComments = jsonObject.getString("comments");

                articleBeanList.add(articleBean);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return articleBeanList;
    }

    /*
    * 读取输入数据流
    * */
    private String readStream(InputStream is) {
        InputStreamReader isr;
        String result = "";
        try {
            String line = "";
            isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            while((line = br.readLine()) != null) {
                result += line;
            }
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}